<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户列表</title>
    <link rel="shortcut icon" href="#"/>
    <link rel="stylesheet" href="css/element-ui.css"/>
    <script src="js/vue.js"></script>
    <script src="js/element-ui.js"></script>
    <script src="js/axios.js"></script>
    <!--    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>-->
    <style>
        .el-dialog__body {
            padding: 0px 20px 20px 20px;
        }

        .avatar-uploader .el-upload {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }

        .avatar-uploader .el-upload:hover {
            border-color: #409EFF;
        }

        .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            line-height: 178px;
            text-align: center;
        }

        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }
    </style>
</head>
<body>
<div id="app" style="height: 600px">
    <h3>用户列表</h3>
    <div>
        <el-form :inline="true" :model="userForm" class="demo-form-inline">
            <el-form-item label="用户名称">
                <el-input v-model="userForm.username" placeholder="用户名称"></el-input>
            </el-form-item>
            <el-form-item label="性别">
                <el-select v-model="userForm.gender" placeholder="性别">
                    <el-option label="请选择" value=""></el-option>
                    <el-option label="男" value="男"></el-option>
                    <el-option label="女" value="女"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSubmit">查询</el-button>
            </el-form-item>
        </el-form>
    </div>

    <div>
        <el-button type="primary" size="mini" @click="openAddUser">添加用户</el-button>
        <el-button type="danger" size="mini" @click="batchDelete">批量删除</el-button>
    </div>

    <!--  表格：装主体数据   -->
    <div>
        <el-table ref="multipleTable" :data="userList" tooltip-effect="dark" style="width: 100%;height: 500px"
                  @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="id" label="用户编号" width="120"></el-table-column>
            <el-table-column prop="username" label="用户名称" width="120"></el-table-column>
            <el-table-column prop="salary" label="年薪" width="120"></el-table-column>
            <el-table-column prop="gender" label="性别" width="60"></el-table-column>
            <el-table-column prop="birth" label="生日" width="120"></el-table-column>
            <el-table-column label="用户头像" width="120">
                <template slot-scope="scope">
                    <el-avatar :size="60" :src="scope.row.avatar" @error="errorHandler" shape="square">
                        <img src="imgs/error.png"/>
                    </el-avatar>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button type="primary" icon="el-icon-edit" circle
                               @click="openUpdateUser(scope.row)"></el-button>
                    <el-button type="danger" icon="el-icon-delete" circle
                               @click="handleDelete(scope.row.id)"></el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>

    <!--  分页   -->
    <br>
    <div class="block">
        <el-pagination background
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"
                       :current-page="userForm.pageNum"
                       :page-sizes="pageSizes"
                       :page-size="userForm.pageSize"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="userForm.total">
        </el-pagination>
    </div>

    <!--添加-->
    <div>
        <!--  对话框   -->
        <el-dialog :title="title" :visible.sync="dialogFormVisible">
            <el-form :model="userForm">
                <el-form-item label="用户名称" :label-width="formLabelWidth">
                    <el-input v-model="userForm.username" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="用户密码" :label-width="formLabelWidth">
                    <el-input v-model="userForm.password" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="用户年薪" :label-width="formLabelWidth">
                    <el-input v-model="userForm.salary" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="用户性别" :label-width="formLabelWidth">
                    <el-radio-group v-model="userForm.gender">
                        <el-radio label="男"></el-radio>
                        <el-radio label="女"></el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="生日" :label-width="formLabelWidth">
                    <el-col :span="11">
                        <el-date-picker type="date" placeholder="选择日期" v-model="userForm.birth"
                                        style="width: 50%;"></el-date-picker>
                    </el-col>
                </el-form-item>
                <el-form-item label="用户头像" :label-width="formLabelWidth">
                    <el-upload
                            class="avatar-uploader"
                            action="/file/upload"
                            :show-file-list="false"
                            :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload">
                        <img v-if="userForm.avatar" :src="userForm.avatar" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancelSubmit">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
            </div>
        </el-dialog>
    </div>

    <!--修改-->
    <div>
        <el-dialog :title="title" :visible.sync="dialogForm">
            <el-form :model="userForm">
                <el-form-item label="用户名称" :label-width="formLabelWidth">
                    <el-input v-model="userForm.username" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="用户密码" :label-width="formLabelWidth">
                    <el-input v-model="userForm.password" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="用户年薪" :label-width="formLabelWidth">
                    <el-input v-model="userForm.salary" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="用户性别" :label-width="formLabelWidth">
                    <el-radio-group v-model="userForm.gender">
                        <el-radio label="男"></el-radio>
                        <el-radio label="女"></el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="生日" :label-width="formLabelWidth">
                    <el-col :span="11">
                        <el-date-picker type="date" placeholder="选择日期" v-model="userForm.birth"
                                        style="width: 50%;"></el-date-picker>
                    </el-col>
                </el-form-item>
                <el-form-item label="用户头像" :label-width="formLabelWidth">
                    <el-upload
                            class="avatar-uploader"
                            action="/file/upload"
                            :show-file-list="false"
                            :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload">
                        <img v-if="userForm.avatar" :src="userForm.avatar" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancelSubmit">取 消</el-button>
                <el-button type="primary" @click="updateUser">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</div>

</body>
<script>
    let vm = new Vue({
        el: '#app',
        created() {
            this.initData();
        },
        data() {
            return {
                pageSizes: [1, 3, 5],
                userForm: {
                    id: 0,
                    username: '',
                    password: '',
                    salary: 0.0,
                    gender: '',
                    birth: '',
                    avatar: '',
                    pageNum: 1,
                    pageSize: 3,
                    total: 0
                },
                userList: [],//用户列表
                ids: [], //批量删除
                title: '',
                dialogFormVisible: false, // 新增用户对话框
                dialogForm: false, // 修改用户对话框
            }
        },
        methods: {
            // ---------------------------修改------------------------
            openUpdateUser(row) {//打开修改用户对话框
                this.title = "修改用户";
                this.dialogForm = true;
                this.userForm.id = row.id;
                this.userForm.username = row.username;
                this.userForm.password = row.password;
                this.userForm.salary = row.salary;
                this.userForm.gender = row.gender;
                this.userForm.birth = row.birth;
                this.userForm.avatar = row.avatar;
            },

            updateUser() {
                if (!this.userForm.username || !this.userForm.password || !this.userForm.salary || !this.userForm.gender || !this.userForm.birth) {
                    this.$message.error('请填写完整的用户信息');
                    return;
                }
                axios({
                    url: "/user/update",
                    method: "post",
                    data: this.userForm
                }).then((res) => {

                    if (res.data.code == 200) {
                        this.$message({
                            type: 'success',
                            message: res.data.msg
                        });
                        this.dialogForm = false;
                        this.reset()
                        this.initData();
                    }
                })
            },

            // ------------------------增加------------------
            reset() {
                this.userForm.id = 0;
                this.userForm.username = '';
                this.userForm.password = '';
                this.userForm.salary = 0.0;
                this.userForm.gender = '';
                this.userForm.birth = '';
                this.userForm.avatar = '';
            },

            openAddUser() {
                this.title = "新建用户";
                this.dialogFormVisible = true;
                this.reset(); // 重置表单
            },

            cancelSubmit() {
                this.dialogFormVisible = false;
                this.dialogForm = false;
                this.reset();
            },

            addUser() {
                // 表单验证
                if (!this.userForm.username || !this.userForm.password || !this.userForm.salary || !this.userForm.gender || !this.userForm.birth || !this.userForm.avatar) {
                    this.$message.error('请填写完整的用户信息');
                    return;
                }
                axios({
                    url: "/user/add",
                    method: "post",
                    data: this.userForm
                }).then((res) => {
                    if (res.data.code == 200) {
                        this.$message({
                            type: 'success',
                            message: res.data.msg
                        });
                        this.dialogFormVisible = false;
                        this.reset();
                        this.initData();
                    } else {
                        this.$message.error(res.data.msg);
                    }
                }).catch(error => {
                    console.error('添加用户失败', error);
                    this.$message.error('添加用户失败，请重试');
                });
            },

            // --------------------------------图片上传-------------------------------------------------------
            handleAvatarSuccess(res, file) {
                this.userForm.avatar = res.data;
            },
            beforeAvatarUpload(file) {
                // 检查文件类型是否为 JPG, PNG 或 WebP
                const isJPGorPNGorWebP = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp';
                const isLt2M = file.size / 1024 / 1024 < 2; // 检查文件大小是否小于 2MB

                if (!isJPGorPNGorWebP) {
                    this.$message.error('上传头像图片只能是 JPG, PNG 或 WebP 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPGorPNGorWebP && isLt2M;
            },

            // -------------------------------------------------------------------
            onSubmit() {
                console.log('submit!');
                this.initData();
            },
            //多选框数据
            handleSelectionChange(val) {
                this.ids = [];
                this.multipleSelection = val;
            },

            // ---------------------------删除------------------------
            handleDelete(userId) {
                this.ids = [];
                this.ids.push(userId);
                this.batchDelete();
                this.ids = [];
            },

            batchDelete() {
                let ids = this.ids;
                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    console.log('-----' + ids);
                    if (ids.length != 1) { // 多选的时候，什么都没有选择
                        // 先从复选框中提取数据复制给ids
                        if (this.multipleSelection != undefined) {
                            this.multipleSelection.forEach((value, index, array) => ids.push(value.id));
                        }
                        // 如果赋值之后，ids还是空，说明没有选
                        if (ids.length === 0) {
                            this.$message({
                                type: 'warning',
                                message: '请先选择要删除的数据'
                            });
                            return;
                        }
                    }
                    axios({
                        url: '/user/delete/' + ids,
                        method: 'POST'
                    }).then(response => {
                        if (response.data.code === 200) {
                            this.$message();
                            this.$message({
                                type: 'success',
                                message: response.data.msg
                            });
                            this.initData();
                        }
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },

            // ---------------------------分页-------------------------
            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
                this.userForm.pageSize = val;
                this.userForm.pageNum = 1;  // 重置到第一页
                this.initData();
            },

            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
                this.userForm.pageNum = val;
                this.initData();
            },

            //错误处理图像
            errorHandler() {
                return true
            },

            //查询所有
            initData() {
                axios({
                    url: '/user/fineUserList',
                    method: 'post',
                    data: this.userForm
                }).then(res => {
                    console.log(res);
                    if (res.data.code == 200) {
                        this.userList = res.data.data.list;
                        this.userForm.pageSize = res.data.data.pageSize;
                        this.userForm.pageNum = res.data.data.pageNum;
                        this.userForm.total = res.data.data.total;

                        // 检查当前页是否有数据
                        if (this.userList.length === 0 && this.userForm.pageNum > 1) {
                            // 如果当前页没有数据，重置到第一页
                            this.userForm.pageNum = this.userForm.pageNum - 1;
                            this.initData(); // 重新加载数据
                        }
                    }
                })
            }
        },
    });
</script>
</html>
